﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Security;
using System.Data;
using Shop4Aggies.Data_Access;

namespace Shop4Aggies.Admin
{
    public partial class ManageUsers : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            
        }

        protected override void OnInit(EventArgs e)
        {
            UpdateUsersGrid();
            base.OnInit(e);
        }

        private int GetNumOrders(string userName)
        {
            using (CommerceEntities db = new CommerceEntities())
            {
                var k = from i in db.Orders
                        where (i.CustomerName == userName)
                        select i;

                return k.Count();
            }
        }

        private int GetNumProducts(string userName)
        {
            MembershipUser mu = Membership.GetUser(userName);

            string puk = mu.ProviderUserKey.ToString();

            using (CommerceEntities db = new CommerceEntities())
            {
                var k = from i in db.Products
                        where (i.VendorID == puk)
                        select i;

                return k.Count();
            }
        }

        protected void UsersGrid_ItemCommand(object source, DataGridCommandEventArgs e)
        {
            if (e.CommandName == "Delete")
            {
                TableCell itemCell = e.Item.Cells[0];
                Membership.DeleteUser(itemCell.Text);
            }

            UpdateUsersGrid();
        }

        protected void UpdateUsersGrid()
        {
            DataSet ds = new DataSet();
            DataTable dt = ds.Tables.Add("Users");

            dt.Columns.Add("User Name", Type.GetType("System.String"));
            dt.Columns.Add("Orders Placed", Type.GetType("System.Int32"));
            dt.Columns.Add("Products Listed", Type.GetType("System.Int32"));

            foreach (MembershipUser user in Membership.GetAllUsers())
            {
                if (user.UserName != Membership.GetUser().UserName)
                {
                    //dont add admin to list
                    DataRow dr = dt.NewRow();

                    dr["User Name"] = user.UserName;
                    dr["Orders Placed"] = GetNumOrders(user.UserName);
                    dr["Products Listed"] = GetNumProducts(user.UserName);

                    dt.Rows.Add(dr);
                }
            }

            UsersGrid.DataSource = ds;
            UsersGrid.DataBind();
        }
    }
}